﻿using System.Collections.Generic;
using System.Linq;
using Core;
using Core.Factory;
using Core.UIItems.Finders;
using Core.UIItems.WindowItems;

namespace Airborne.ScrumPoker.Presentation.AutomationTests
{
    public abstract class TestBase
    {

        private static IDictionary<string, Application> Applications = new Dictionary<string, Application>();

        protected static Application GetApplication(string location)
        {
            if (!Applications.ContainsKey(location))
            {
                Application application = Launch(location);
                Applications.Add(location, application);
            }
            return Applications[location];

        }

        private static Application Launch(string location)
        {
            return Application.Launch(location);
        }

        protected static Window OpenWindow(Application application, string automationId)
        {
            SearchCriteria windowId = SearchCriteria.ByAutomationId(automationId);
            application.WaitWhileBusy();
            return application.GetWindow(windowId, InitializeOption.NoCache);
        }

        protected static void Close(Application application)
        {
            var foundApplication = (from a in Applications
                                    where a.Value == application
                                    select a).FirstOrDefault();
            if (foundApplication.Value != null)
            {
                Applications.Remove(foundApplication);
            }
            application.Kill();
        }

        protected static void Close(string location)
        {
            if( Applications.ContainsKey( location ))
            {
                Close( Applications[location]);
            }
        }
    }
}
